/*
 * @(#)IP.java
 *
 */

package diablo3;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import diablo3.support.Util;

/**
 * description
 * @author  huangyixiang
 * @version 2012-8-27
 */
public class IP {
	
	private static final Log LOG = LogFactory.getLog(IP.class);
	
	public static void main(String[] args) {
			LOG.info(getOutIPAddress()[1]);
	}
	
	public static final String[] getOutIPAddress(){
		String[] s = new String[2];
//		s[1] = "http://www.ip138.com/ : " + getOutIPAddress("http://www.ip138.com/" , ipReg);
		s[1] = "http://tool.chinaz.com/Ip/ : " + (s[0] = getOutIPAddress("http://tool.chinaz.com/Ip/" , null));
		s[1] += "<br/>" + "http://www.cz88.net/ : " + getOutIPAddress("http://www.cz88.net/" , null);
		s[1] += "<br/>" + "http://www.123cha.com/ : " + getOutIPAddress("http://www.123cha.com/" , null);
		s[1] += "<br/>" + "http://www.viewip.info/ : " + getOutIPAddress("http://www.123cha.com/" , null);
		return s;
	}
	
	public static final String getOutIPAddress(String url ,  String ipReg){
		String ip = null;
		if(Util.isBlank(ipReg)){
			ipReg = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
		}	
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(url);
		for(int i = 0; i < 3 ; i++){
			try {
				if(client.executeMethod(method) != 200){
					LOG.info("retry getOutIPAddress " + i);
					continue;
				}
				String body = method.getResponseBodyAsString();
				Pattern p = Pattern.compile(ipReg);
				Matcher m = p.matcher(body);
				if(!m.find()){
					LOG.info("正则不匹配:" + " url: " + url + ",ipReg:" + ipReg);
//					LOG.info(body);
					return null;
				}
				ip = m.group();
				LOG.info(url + " : " + ip);
				return ip;
				
			} catch (HttpException e) {
				// TODO Auto-generated catch block
				LOG.info(e.getMessage(), e);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				LOG.info(e.getMessage(), e);
			}
		}
		return ip;
	}

}
